local http_parse = require "http_plugin.http"

local router = {}

local function urlencode(s)
    return string.gsub(s, "([^%w%.%-])", function(c) return string.format("%%%02X", string.byte(c)) end)
end

local function urldecode(s)
    return string.gsub(string.gsub(s, "+", " "), "%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end)
end

router["/api/liuyan"] = function(conn, req, res)
    if req.content ~= nil and #req.content ~= 0 then
        req.content = urldecode(req.content)
        local file = io.open("liuyanban.txt", "a+")
        file:write(req.content)
        file:write("\r\n")
        file:close()
    end
    res.content = "OK"
end

function http_handler(conn, data)
    local req = {header = {}}
    local ret = http_parse.request_decode(data,req)
	if ret <= 0 then
        return
    end
    local res = {version = "HTTP/1.1", header={}}
    local call = router[req.uri]
    if call ~= nil then
        res.status_code = 200
        res.status = "OK"
        call(conn, req, res)
    else
        -- 404 Not Found
        -- res.status_code = 404
        -- res.status = "Not Found"
        res.status_code = 302
        res.status = "Found"
        res.header["Location"] = "/"
    end
    local peer_ip, peer_port = conn:peer_addr()
    Log(2, peer_ip, req.method, req.uri.."?"..req.qeury, res.status_code, res.status)
    local res_stream = http_parse.response_encode(res)
    conn:send(res_stream)
    conn:close()
end